const db = require("../db")

// 查看成绩
exports.ssscore = (req, res) => {
  const sql = `select * from sc5342.student_score_view where s_no=${req.body.sno} order by c_type desc, c_no;`
  db.query(sql, function (err, results) {
    if (err) return res.cc({msg: err.sqlMessage})
    results.forEach((e, i) => {
      results[i].c_type = e.c_type ? '必修' : '选修'
    })
    res.cc(results, 200)
  })
}

// 查看课程
exports.sscourse = (req, res) => {
  const sql = `select * from sc5342.student_course_view where s_no=${req.body.sno} order by c_type desc, c_no;`
  db.query(sql, function (err, results) {
    if (err) return res.cc({msg: err.sqlMessage})
    results.forEach((e, i) => {
      results[i].c_type = e.c_type ? '必修' : '选修'
    })
    res.cc(results, 200)
  })
}

// 查看选修课
exports.sccourse = (req, res) => {
  const sql = `select * from sc5342.choose_course_view order by c_no, t_no;`
  db.query(sql, function (err, results) {
    if (err) return res.cc({msg: err.sqlMessage})
    res.cc(results, 200)
  })
}

// 选课处理函数
exports.choosecourse = (req, res) => {
  const userinfo = req.body
  const sql = `insert into sc5342.student_course5342(s_no, c_no, t_no) values('${userinfo.sno}', '${userinfo.cno}', '${userinfo.tno}');`
  db.query(sql, function (err, results) {
    if (err) return res.cc({msg: '选课失败'})
    res.cc({msg: '选课成功'}, 200)
  })
}

// 取消选课处理函数
exports.cancelcourse = (req, res) => {
  const userinfo = req.body
  const nature = `Cancelcourse('${userinfo.sno}', '${userinfo.tno}', '${userinfo.cno}')`
  const sql = `select ${nature};`
  db.query(sql, function (err, results) {
    if (err) return res.cc({msg: err.sqlMessage})
    if (results[0][nature]) return res.cc({msg: '取消成功!'}, 200)
    res.cc({msg: '取消失败!'})
  })
}